
import 'dart:convert';

class EventInfo {
  String appid;
  String appName;
  String packageName;
  String? traceId;
  String eventId;
  int eventTime;
  int? costTime;
  String eventType;
  int platform;
  String? userId;
  String? deviceId;
  String deviceInfo;
  String? clientId;
  String appVersion;
  String? curPage;
  String? prePage;
  String? extraInfo;

  EventInfo({
    required this.appid,
    required this.appName,
    required this.packageName,
    required this.eventId,
    required this.eventTime,
    required this.eventType,
    required this.platform,
    required this.deviceInfo,
    required this.appVersion,
    this.clientId,
    this.costTime,
    this.traceId,
    this.deviceId,
    this.userId,
    this.curPage,
    this.prePage,
    this.extraInfo,
  });

  //Must have a factory named constructor fromMap
  factory EventInfo.fromMap(Map<String, dynamic> map) {
    return EventInfo(
      appid: map["appid"] as String,
      appName: map["appName"] as String,
      packageName: map["packageName"] as String,
      traceId: map['traceId'] as String,
      eventId: map['eventId'] as String,
      eventTime: map['eventTime'] as int,
      costTime: map['costTime'] as int,
      eventType: map['eventType'] as String,
      platform: map['platform'] as int,
      userId: map['userId'] as String,
      clientId: map['clientId'] as String,
      deviceId: map['deviceId'] as String,
      deviceInfo: map['deviceInfo'] as String,
      appVersion: map['appVersion'] as String,
      curPage: map['curPage'] as String,
      prePage: map['prePage'] as String,
      extraInfo: map['extraInfo'] as String,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'appid': appid,
      'app_name': appName,
      'package_name': packageName,
      'trace_id': traceId ?? "",
      'event_id': eventId,
      'event_time': eventTime,
      'cost_time': costTime ?? 0,
      'event_type': eventType,
      'platform': platform,
      'user_id': userId ?? "",
      'client_id': clientId ?? "",
      'device_id': deviceId ?? "",
      'device_info': deviceInfo,
      'app_version': appVersion,
      'cur_page': curPage ?? "",
      'pre_page': prePage ?? "",
      'extra_info': extraInfo is String ? extraInfo : jsonEncode(extraInfo ?? ""),  // 确保 JSON 对象被序列化为字符串
    };
  }

  @override
  Map<String, dynamic> toJson() {
    return {
      'traceId': traceId,
      'eventId': eventId,
      'eventTime': eventTime,
      'eventType': eventType,
      'platform': platform,
      'userId': userId ?? "",
      'deviceInfo': deviceInfo,
      'appVersion': appVersion,
      'curPage': curPage ?? "",
      'prePage': prePage ?? "",
      'extraInfo': extraInfo ?? "",
    };
  }

}
